package com.second.order.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.second.order.dao.OrderCostDao;
import com.second.order.feign.ClientFeign;
import com.second.order.pojo.entity.OrderCost;
import com.second.order.pojo.vo.RecordAndCostVo;
import com.second.order.service.OrderCostService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * (OrderCost)表服务实现类
 *
 * @author lvyongqi
 * @since 2021-08-02 09:05:06
 */
@Service("orderCostService")
public class OrderCostServiceImpl extends ServiceImpl<OrderCostDao, OrderCost> implements OrderCostService {

    /**
     * 客户微服务调用接口
     */
    @Resource
    private ClientFeign clientFeign;

    @Resource OrderCostDao orderCostDao;

    @Override
    public boolean updateCost(RecordAndCostVo recordAndCostVo) {
        OrderCost orderCost = new OrderCost();
        // 先判断客户支付过程中是否使用了优惠券
        if (recordAndCostVo.getCouponId() == null || recordAndCostVo.getCouponId() == 0) {
            // 未使用优惠券，设置应付金额与原价保持一致
            orderCost.setAmountPayable(recordAndCostVo.getOriginalPrice());
            // 设置优惠券id
            orderCost.setCouponId(0);
        }else {
            // 使用了优惠券,首先根据优惠券id查出优惠金额
            Integer couponAmount = clientFeign.getCouponAmountById(recordAndCostVo.getCouponId());
            // 设置应付金额为原价减去优惠金额
            double amountPayable = recordAndCostVo.getOriginalPrice() - couponAmount;
            orderCost.setAmountPayable(amountPayable);
            // 设置优惠券id
            orderCost.setCouponId(recordAndCostVo.getCouponId());
        }
        // 设置订单费用流水编号
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
        String format = simpleDateFormat.format(new Date());
        orderCost.setPaymentStream(format + (int)((Math.random()*9+1)*10000000));
        // 设置费用id
        orderCost.setCostId(recordAndCostVo.getOrderId());
        // 设置支付方式
        orderCost.setPaymentMethod(recordAndCostVo.getPaymentMethod());
        // 订单原价
        orderCost.setOriginalPrice(recordAndCostVo.getOriginalPrice());
        // 实付金额
        orderCost.setPaidAmount(recordAndCostVo.getPaidAmount());
        // 会员id
        orderCost.setClientId(recordAndCostVo.getClientId());
        return orderCostDao.updateCost(orderCost);

    }

}
